package com.baseweb.webadmin.controller.app;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.Constants;
import com.baseweb.webadmin.core.model.bvo.UserForm;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.CheckCodeUtil;
import com.baseweb.webadmin.core.util.DateUtil;
import com.baseweb.webadmin.core.util.MD5Util;
import com.baseweb.webadmin.core.util.RandCharUtil;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * Created by dsy62 on 2017-08-08.
 */
@Controller
@RequestMapping(value = "/appApiLogin")
public class LoginAppController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map<String, Object> login(@RequestParam(value = "mobile", defaultValue = "") String mobile,
                                     @RequestParam(value = "password", defaultValue = "") String password){

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)){
            return fail("数据不能为空!");
        }else {
            User user = userService.findUserByNamePassWord(mobile,MD5Util.Md5(password));
            if(user != null){
                if(user.getStatus()== 1 || user.getStatus() == 7){
                    return success(user,"登录成功");
                }else {
                    return fail("用户被锁定,请联系客服!");
                }
            }else {
                return fail("登录失败");
            }
        }
    }

    /**
     * 注册
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Map<String,Object> register(@ModelAttribute()User user){
        /**
         * 查询该手机的用户是否已经注册了！
         */
        User userIsO = userService.selectByName(user.getUsername());
        /**
         * 手机号码和发送的手机验证码一致性验证
         */
        String result = CheckCodeUtil.verify(user.getUsername(), user.getValidate_code());
        /**
         * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
         */
        if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {
            /**
             * 对该手机号码的查询结果进行判断。如果数据库存在
             */
            if (null != userIsO) {
                return fail("手机号码已被注册");
            }else{
                String pw = user.getPassword();
                user.setPassword(MD5Util.Md5(pw.trim()));
                user.setToken(MD5Util.Md5(user.getPassword()+"boyi"+ DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                user.setStatus(7);
                user.setCreateTime(new DateTime());
                user.setUpdateTime(new DateTime());
                user.setOrderCount(0);
                user.setCoins(50);
                user.setMoney(new BigDecimal("0.00"));
                user.setLevelCoins(0);
                user.setIsHot(0);

                if(userService.insertUser(user) == 1){
                    User userR = userService.selectByUserName(user.getUsername());
                    if(userR.getUserType() == 2){
                        //写角色
                        //权限角色
                        roleService.insertIntoRoleUser(userR.getId(),3);
                        //职业角色
                        roleService.insertIntoRoleUser(userR.getId(),10);
                        //默认的佣金角色
                        roleService.insertIntoRoleUser(user.getId(),16);
                        //默认的信誉角色
                        roleService.insertIntoRoleUser(user.getId(),17);

                    }else if(userR.getUserType() == 3){
                        //写角色
                        //权限角色
                        roleService.insertIntoRoleUser(userR.getId(),4);
                        //职业角色
                        roleService.insertIntoRoleUser(userR.getId(),10);
                        //默认的佣金角色
                        roleService.insertIntoRoleUser(user.getId(),16);
                        //默认的信誉角色
                        roleService.insertIntoRoleUser(user.getId(),17);

                    }
                    return success("注册成功");
                }else{
                    return fail("操作失败，请重试");
                }
            }
        }else{
            return fail("手机验证码不正确");
        }
    }

    /**
     * 注册详细资料
     */
    @ResponseBody
    @RequestMapping(value = "/tenants", method = RequestMethod.POST)
    public Map<String,Object> tenants(@ModelAttribute()UserForm userForm){
        if(userForm.getUsername() != null){
            User user = userService.selectByName(userForm.getUsername());
            user.setCnName(userForm.getUnionName());
            user.setProvince(userForm.getS_province());
            user.setCity(userForm.getS_city());
            user.setArea(userForm.getS_county());

            int occupationId = 10;
            //职业角色
            if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                occupationId = Integer.parseInt(userForm.getOccupation());
                if(occupationId == 11){
                    user.setBizWorkType(1);
                }else if(occupationId == 12){
                    user.setBizWorkType(3);
                }else if(occupationId == 13){
                    user.setBizWorkType(4);
                }else if(occupationId == 14){
                    user.setBizWorkType(2);
                }else if(occupationId == 15){
                    user.setBizWorkType(5);
                }else {
                    user.setBizWorkType(999);
                }
            }

            if(userService.updateUser(user) != 1){
                return fail("操作失败，请重试");
            }else {
                //写角色
                //权限角色
                if(userForm.getDiction() !=null && !"".equals(userForm.getDiction())){
                    if(roleService.updateIntoRoleUser(Integer.parseInt(userForm.getDiction()),user.getId(),"1") == 1){
                        //职业角色
                        if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                            if(roleService.updateIntoRoleUser(Integer.parseInt(userForm.getOccupation()),user.getId(),"2") == 1){
                                return success("注册成功");
                            }else {
                                return fail("职业角色操作失败，请重试");
                            }
                        }else{
                            return fail("职业角色不能为空");
                        }
                    }else {
                        return fail("权限角色操作失败，请重试");
                    }
                }else{
                    return fail("权限角色不能为空");
                }
            }
        }else {
            return fail("登录账号不能为空");
        }
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @RequestMapping(value = "/editPassWord", method = RequestMethod.POST)
    public Map<String,Object> editPassWord(@ModelAttribute()User user){
        /**
         * 手机号码和发送的手机验证码一致性验证
         */
        String result = CheckCodeUtil.verify(user.getUsername(), user.getValidate_code());
        /**
         * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
         */
        if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {
            User userR = userService.findUserByUserName(user.getUsername());
            if(userR != null){
                userR.setPassword(MD5Util.Md5(user.getPassword()));
                if(userService.updateUser(userR) == 1){
                    return success("修改成功");
                }else{
                    return fail("修改失败");
                }
            }else{
                return fail("账号不存在");
            }
        }else{
            return fail("手机验证码不正确");
        }
    }
}
